<?php

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(360*60);
ini_set('memory_limit', '512M');

require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
require_once dirname(__FILE__). '/util/TimeUtil.php';



$g_start = microtime(true);

$dbconn = Connection::getInstance();

if(count($argv) ==  2) {
	$site = $argv[1];
}else{
	echo "Usage: php stat_ltv_new.php [site_id]\n";
	exit;
}




//$site = 1;





$userInfos = getUserInfos($site, $dbconn);
$userInfos = useIdAsKey($userInfos);
traversalDirectoryFile($userInfos, RAW_DATA_ROOT);
foreach($userInfos as $k=>$v){
	
	if(isset($v['full_reg_time'])){
		$userInfos[$k]['registrationToProfileTime'] = (($v['full_reg_time'] - $v['created']) / 60) . 'minutes' ;
	}else{
		$userInfos[$k]['registrationToProfileTime'] = '';
	}
	unset($userInfos[$k]['full_reg_time']);
	
	if(isset($v['confirmed_coreg_time'])){
		$userInfos[$k]['registrationToConfirmTime'] = (($v['confirmed_coreg_time'] - $v['created']) /60) . 'minutes';
	}else{
		$userInfos[$k]['registrationToConfirmTime'] = '';
	}
	unset($userInfos[$k]['confirmed_coreg_time']);
	
	$userInfos[$k]['created'] = date('Y-m-d H:i:s', $v['created']);
	$userInfos[$k]['last_visit'] = date('Y-m-d H:i:s', $v['last_visit']);
	
	$userInfos[$k]['session2012-01'] = isset($v['sessionNum']['2012-01'])? $v['sessionNum']['2012-01'] : 0;
	$userInfos[$k]['session2012-02'] = isset($v['sessionNum']['2012-02'])? $v['sessionNum']['2012-02'] : 0;
	$userInfos[$k]['session2012-03'] = isset($v['sessionNum']['2012-03'])? $v['sessionNum']['2012-03'] : 0;
	$userInfos[$k]['session2012-04'] = isset($v['sessionNum']['2012-04'])? $v['sessionNum']['2012-04'] : 0;
	unset($userInfos[$k]['sessionNum']);
	
	$userTokenNum = getUserTokenFromDb($k, $dbconn);
	$userInfos[$k]['token2012-01'] = isset($userTokenNum['2012-01'])? $userTokenNum['2012-01'] : 0;
	$userInfos[$k]['token2012-02'] = isset($userTokenNum['2012-02'])? $userTokenNum['2012-02'] : 0;
	$userInfos[$k]['token2012-03'] = isset($userTokenNum['2012-03'])? $userTokenNum['2012-03'] : 0;
	$userInfos[$k]['token2012-04'] = isset($userTokenNum['2012-04'])? $userTokenNum['2012-04'] : 0;
	
//	$userInfos[$k]['token2011-09'] = isset($v['tokenNum']['2011-09'])? $v['tokenNum']['2011-09'] : 0;
//	$userInfos[$k]['token2011-10'] = isset($v['tokenNum']['2011-10'])? $v['tokenNum']['2011-10'] : 0;
//	$userInfos[$k]['token2011-11'] = isset($v['tokenNum']['2011-11'])? $v['tokenNum']['2011-11'] : 0;
//	$userInfos[$k]['token2011-12'] = isset($v['tokenNum']['2011-12'])? $v['tokenNum']['2011-12'] : 0;
//	$userInfos[$k]['token2012-01'] = isset($v['tokenNum']['2012-01'])? $v['tokenNum']['2012-01'] : 0;
//	$userInfos[$k]['token2012-02'] = isset($v['tokenNum']['2012-02'])? $v['tokenNum']['2012-02'] : 0;
//	unset($userInfos[$k]['tokenNum']);
	
	$userInfos[$k]['won2012-01'] = isset($v['wonNum']['2012-01'])? $v['wonNum']['2012-01'] : 0;
	$userInfos[$k]['won2012-02'] = isset($v['wonNum']['2012-02'])? $v['wonNum']['2012-02'] : 0;
	$userInfos[$k]['won2012-03'] = isset($v['wonNum']['2012-03'])? $v['wonNum']['2012-03'] : 0;
	$userInfos[$k]['won2012-04'] = isset($v['wonNum']['2012-04'])? $v['wonNum']['2012-04'] : 0;
	unset($userInfos[$k]['wonNum']);
}
$csvHeader = array('uID', 'Publisher', 'Placement', 'Register Time', 'Last Visit', 'Birthday', 'Gender', 'total tokens', 'total won', 'basic reg coreg', 'profiling coreg end', 'confirm coreg end', 'registration To Profile Time', 'registration To Confirm Time', 
				   "Total # of sessions in Jan '12", "Total # of sessions in Feb '12", "Total # of sessions in Mar '12", "Total # of sessions in Apr '12", 
				   "Total # of  tokens earned  in Jan '12", "Total # of  tokens earned  in Feb '12", "Total # of  tokens earned  in Mar '12", "Total # of  tokens earned  in Apr '12", 
				   "Total winnings $ in Jan '12", "Total winnings $ in Feb '12", "Total winnings $ in Mar '12", "Total winnings $ in Apr '12");
sendCsv($userInfos, $csvHeader, 'LTV_' . $site . '.csv');

echo 'Totally: '. (microtime(true) - $g_start) . " seconds \n";
echo "memory: " . memory_get_peak_usage() . " bytes \n";

function getUserInfos($site, $db) 
{
	global $g_start;
//	$sql = " SELECT u.id, u.pub, u.pla, u.created, u.last_visit, u.gender, u.birthday, u.zipcode, SUM(r.credit) AS credits, s.domain FROM users u LEFT JOIN sites s ON u.site_id=s.id LEFT JOIN rewards r ON u.id=r.user_id WHERE s.domain=? GROUP BY u.id ";
	try{
//		$result = $db->query($sql, array($site));
//		return $result;
		if ($site == 1)
		{
			$domain = 'cashdazzle.com';
		}
		else if ($site == 2)
		{
			$domain = 'lalaloot.com';
		}
		else if ($site == 3)
		{
			$domain = 'mommymoolah.com';
		}
		
		$time_start = strtotime('2012-01-01 00:00:00');
		$time_end = strtotime('2012-02-01 00:00:00');
		$sql = " SELECT id, pub, pla, created, last_visit, birthday, gender, 0 as credits, won FROM users WHERE site_id=? AND (created>=? AND created<?) ";
		$users = $db->query($sql, array($site, $time_start, $time_end));
		echo "Total Users: " . count($users) . "\t" . (microtime(true) - $g_start) . "\n";
		$count = 0;
		foreach ($users as &$user)
		{
			$sql = 'select sum(credit) as credits from rewards where user_id=?';
			$result = $db->query($sql, array($user['id']));
			$user['credits'] = $result[0]['credits'];
			$count ++;
			if ($count % 10000 == 0)
			{
				echo "finished ". $count . "\t" . (microtime(true) - $g_start) . "\n";
			}
			
			$user['basic_reg_coreg_end'] = 0;
			$user['profiling_coreg_end'] = 0;
			$user['confirm_coreg_end'] = 0;
		}
		return $users;
	}catch(Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function useIdAsKey($arr)
{
	$ret = array();
	foreach($arr as $k=>$v){
		$ret[$v['id']] = $v;
	}
	
	return $ret;
}

function getUserTokenFromDb($uid, $db)
{
	try{
		$sql = " SELECT credit AS token, created FROM rewards WHERE user_id=? ";
		$result = $db->query($sql, array($uid));
		
		$tokenNum = array();
		foreach($result as $k=>$v){
			if($v['created'] >= strtotime('2012-01') && $v['created'] <= strtotime('2012-04-30 23:59:59')){
				$timeFrame = date('Y-m', $v['created']);
				if(!isset($tokenNum[$timeFrame])){
					$tokenNum[$timeFrame] = $v['token'];
				}else{
					$tokenNum[$timeFrame] += $v['token'];
				}
			}
		}

		return $tokenNum;
		
	}catch(Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}


function traversalDirectoryFile(&$userInfos, $path)
{
	$handle = opendir($path);
	while($file = readdir($handle)){
  		if($file=="."||$file=="..")
   		continue;
  		$newFilePath = $path . DIRECTORY_SEPARATOR . $file;
  		if(is_dir($newFilePath)){
  			if(in_array(basename($newFilePath), array('2012_01', '2012_02', '2012-03', '2012_04'))){
// 				echo "document---------->".$newFilePath."<br>";
	   			traversalDirectoryFile($userInfos, $newFilePath);
  			}
  		}
  		if(is_file($newFilePath)){
//  			echo "File-------------->  ".$newFilePath."<br>";
  			$file_handle = fopen($newFilePath, 'r');
  			if ($file_handle) {
				while (!feof($file_handle)) {
					$line = fgets($file_handle);
					if (!empty($line)) {
						//echo $line."<br>";
						$line_args = explode(':', $line);
						$time = isset($line_args[0])? $line_args[0] : 0;
						$session = isset($line_args[2])? $line_args[2] : '';
						$uid = isset($line_args[3])? $line_args[3] : '';
						$event = isset($line_args[4])? $line_args[4] : '';
						if(count($line_args) == 24){
							$monetization = isset($line_args[16])? $line_args[16] : 0;
							$won = isset($line_args[17])? $line_args[17] : 0;
							$token = isset($line_args[20])? $line_args[20] : 0;
						}else if(count($line_args) == 28){
							$monetization = isset($line_args[16])? $line_args[16] : 0;
							$won = isset($line_args[17])? $line_args[17] : 0;
							$token = isset($line_args[20])? $line_args[20] : 0;
						}else if(count($line_args) == 29){
							$monetization = isset($line_args[17])? $line_args[17] : 0;
							$won = isset($line_args[18])? $line_args[18] : 0;
							$token = isset($line_args[21])? $line_args[21] : 0;
						}else if(count($line_args) == 30){
							$monetization = isset($line_args[18])? $line_args[18] : 0;
							$won = isset($line_args[19])? $line_args[19] : 0;
							$token = isset($line_args[22])? $line_args[22] : 0;
						}else if(count($line_args) == 31){
							$monetization = isset($line_args[19])? $line_args[19] : 0;
							$won = isset($line_args[20])? $line_args[20] : 0;
							$token = isset($line_args[23])? $line_args[23] : 0;
						}else{
							$token = 0;
							$won = 0;
						}
						if(isset($userInfos[$uid])){
							$timeFrame = date('Y-m', $time);
							if($session != ''){
								if(!isset($userInfos[$uid]['sessionNum'][$timeFrame])){
									$userInfos[$uid]['sessionNum'][$timeFrame] = 1;
								}else{
									$userInfos[$uid]['sessionNum'][$timeFrame]++;
								}
							}
//							if($token != 0 && $token != ''){
//								if(!isset($userInfos[$uid]['tokenNum'][$timeFrame])){
//									$userInfos[$uid]['tokenNum'][$timeFrame] = 1;
//								}else{
//									$userInfos[$uid]['tokenNum'][$timeFrame]++;
//								}
//							}
							if($won != 0 || $won != ''){
								if(!isset($userInfos[$uid]['wonNum'][$timeFrame])){
									$userInfos[$uid]['wonNum'][$timeFrame] = 1;
								}else{
									$userInfos[$uid]['wonNum'][$timeFrame]++;
								}
							}
							
							if($event == 'full_reg'){
								$userInfos[$uid]['full_reg_time'] = $time;
							}else if($event == 'basic_reg_coreg'){
								$userInfos[$uid]['basic_reg_coreg_end'] = 1;
							}else if($event == 'profiling_coreg_end'){
								$userInfos[$uid]['profiling_coreg_end'] = 1;
							}else if($event == 'confirm_coreg_end'){
								$userInfos[$uid]['confirm_coreg_end'] = 1;
							}else if($event == 'confirmed_coreg'){
								$userInfos[$uid]['confirmed_coreg_time'] = $time;
							}
						}
					}
				}
				fclose($file_handle);
			}
  		}
 	}
 	closedir($handle);
}

function sendCsv($data, $headers, $filename) {
	$output = fopen(dirname(__FILE__) . DIRECTORY_SEPARATOR . $filename, 'w');	//var_dump('output file------>' . RAW_DATA_ROOT . DIRECTORY_SEPARATOR . $filename);
	fputcsv($output, $headers);
	if(!empty($data)){
		foreach ($data as $row) {
			fputcsv($output, $row);
		}			
	}

	
	fclose($output);
}





